package com.block.merchant.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.exception.NotifyExceptionService;
import com.block.datapush.factory.PushApiFactory;
import com.block.datapush.model.result.StarInfoResult;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.merchant.service.IMatchUpdateStartLeveService;
import com.block.merchant.service.IMerchantBaseInfoService;
import com.block.merchant.service.IMerchantDataPushInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class MatchUpdateStartLeveService implements IMatchUpdateStartLeveService {

    @Autowired
    NotifyExceptionService notifyExceptionService;

    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    IMerchantDataPushInfoService merchantDataPushInfoService;

    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Override
    public JSONObject update(Integer infoId, Map<String, String[]> parameterMap, String paramContent) {

        String message = StrUtil.format("【机构星级回调】请求数据展示【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            JSONObject error = getError("传入的信息为空");
            return error;
        }
        String mobileMd5 = jsonObjectParamContent.getString("mobileMd5");
        Integer startLevel = jsonObjectParamContent.getInteger("startLevel");
        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);
        try {
            if (ObjectUtil.isEmpty(merchantBaseInfo)) {
                JSONObject error = getError("infoId有误");
                return error;
            }

            if (ObjectUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.CRM.getValue())) {
                JSONObject error = getError("机构类型错误，该类型不可修改星级");
                return error;
            }

            if (StrUtil.isEmpty(mobileMd5)) {
                JSONObject error = getError("传入的手机号MD5为空");
                return error;
            }

            if (startLevel == null) {
                JSONObject error = getError("传入的星级有误");
                return error;
            }
            if (!isInRange(startLevel)) {
                JSONObject error = getError("该星级不在取值范围之内");
                return error;
            }

            MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);
            if (ObjectUtil.isEmpty(memberSourceInfo)) {
                JSONObject error = getError("传入的手机号MD5有误");
                return error;
            }
            Long uid = memberSourceInfo.getUid();
            Integer startLevelOld = memberSourceInfo.getStartLevel();
            if (startLevelOld != -1) {
                JSONObject error = getError("不可重复修改该用户星级");
                return error;
            }
            List<MerchantDataPushInfo> merchantDataPushInfoList = merchantDataPushInfoMapper.selectMerchantDataPushInfoByUidAndInfoId(infoId, uid);
            if (merchantDataPushInfoList.size() == 0) {
                JSONObject error = getError("该用户不可修改星级");
                return error;
            }
            memberSourceInfoMapper.startLeverUpdate(uid, startLevel);
            return getSuccess("星级回传成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("STARTLEVEL_API_UPDATE", "修改星级异常", message, exception);
        }

        return getError("修改星级异常");
    }


    @Override
    public JSONObject update1(Integer infoId, Map<String, String[]> parameterMap, String paramContent) {

        String message = StrUtil.format("【机构星级回调】请求数据展示【infoId】{}【parameterMap】{}【paramContent】{}", infoId, JSON.toJSONString(parameterMap), paramContent);
        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);
        try {
            if (ObjectUtil.isEmpty(merchantBaseInfo)) {
                JSONObject error = getError("infoId有误");
                return error;
            }

            StarInfoResult starInfoResult = PushApiFactory.getExtService(merchantBaseInfo.getFactoryType()).handleStarInfo(merchantBaseInfo, parameterMap, paramContent);

            if (ObjectUtil.isEmpty(starInfoResult)) {
                JSONObject error = getError("传入的信息为空");
                return error;
            }

            String mobileMd5 = starInfoResult.getMobileMd5();
            Integer startLevel = starInfoResult.getStarLevel();

            if (ObjectUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.CRM.getValue())) {
                JSONObject error = getError("机构类型错误，该类型不可修改星级");
                return error;
            }

            if (StrUtil.isEmpty(mobileMd5)) {
                JSONObject error = getError("传入的手机号MD5为空");
                return error;
            }

            if (startLevel == null) {
                JSONObject error = getError("传入的星级有误");
                return error;
            }
            if (!isInRange(startLevel)) {
                JSONObject error = getError("该星级不在取值范围之内");
                return error;
            }

            MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);
            if (ObjectUtil.isEmpty(memberSourceInfo)) {
                JSONObject error = getError("传入的手机号MD5有误");
                return error;
            }
            Long uid = memberSourceInfo.getUid();
            Integer startLevelOld = memberSourceInfo.getStartLevel();
            if (startLevelOld != -1) {
                JSONObject error = getError("不可重复修改该用户星级");
                return error;
            }
            List<MerchantDataPushInfo> merchantDataPushInfoList = merchantDataPushInfoMapper.selectMerchantDataPushInfoByUidAndInfoId(infoId, uid);
            if (merchantDataPushInfoList.size() == 0) {
                JSONObject error = getError("该用户不可修改星级");
                return error;
            }else {
                merchantDataPushInfoList.stream().forEach(updateStartLever -> {
                    MerchantDataPushInfo merchantDataPushInfo = new MerchantDataPushInfo();
                    merchantDataPushInfo.setId(updateStartLever.getId());
                    merchantDataPushInfo.setStartLevel(startLevel);
                    merchantDataPushInfoMapper.updateById(merchantDataPushInfo);
                });
            }
            memberSourceInfoMapper.startLeverUpdate(uid, startLevel);
            return getSuccess("星级回传成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("STARTLEVEL_API_UPDATE", "修改星级异常", "", exception);
        }

        return getError("修改星级异常");
    }


    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    public JSONObject getSuccess(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", message);
        return returnObject;
    }

    public static boolean isInRange(int value) {
        return value >= 0 && value <= 5;
    }


}
